package jfconfig;

/**
 * Created : Mar 16, 2012
 *
 * @author pquiring
 */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import javaforce.*;

public class ProxyRuleDialog extends javax.swing.JDialog implements KeyListener {

  /**
   * Creates new form ProxyRuleDialog
   */
  public ProxyRuleDialog(java.awt.Frame parent, boolean modal, ProxyPanel.Rule rule) {
    super(parent, modal);
    initComponents();
    setPosition();
    if (rule == null) return;
    enabled.setSelected(rule.enabled);
    ip.setText(rule.ip);
    if (!rule.urls.equals("all")) {
      some.setSelected(true);
      urls.setText(rule.urls.replaceAll(",", "\n"));
    }
    ip.addKeyListener(this);
  }

  /**
   * This method is called from within the constructor to initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is always
   * regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    buttonGroup1 = new javax.swing.ButtonGroup();
    jLabel1 = new javax.swing.JLabel();
    ip = new javax.swing.JTextField();
    all = new javax.swing.JRadioButton();
    some = new javax.swing.JRadioButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    urls = new javax.swing.JTextArea();
    accept = new javax.swing.JButton();
    cancel = new javax.swing.JButton();
    enabled = new javax.swing.JCheckBox();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Proxy Rule");

    jLabel1.setText("Client IP:");

    ip.setText("127.0.0.1/32");

    buttonGroup1.add(all);
    all.setSelected(true);
    all.setText("Allow access to all sites");
    all.addItemListener(new java.awt.event.ItemListener() {
      public void itemStateChanged(java.awt.event.ItemEvent evt) {
        allItemStateChanged(evt);
      }
    });

    buttonGroup1.add(some);
    some.setText("Allow access to following sites (list one domain per line):");
    some.addItemListener(new java.awt.event.ItemListener() {
      public void itemStateChanged(java.awt.event.ItemEvent evt) {
        someItemStateChanged(evt);
      }
    });

    urls.setColumns(20);
    urls.setEditable(false);
    urls.setRows(5);
    jScrollPane1.setViewportView(urls);

    accept.setText("Accept");
    accept.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        acceptActionPerformed(evt);
      }
    });

    cancel.setText("Cancel");
    cancel.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        cancelActionPerformed(evt);
      }
    });

    enabled.setSelected(true);
    enabled.setText("Enabled");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jScrollPane1)
          .addGroup(layout.createSequentialGroup()
            .addComponent(jLabel1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(ip))
          .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addGap(0, 0, Short.MAX_VALUE)
            .addComponent(cancel)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(accept))
          .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(all)
              .addComponent(some)
              .addComponent(enabled))
            .addGap(0, 0, Short.MAX_VALUE)))
        .addContainerGap())
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(enabled)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel1)
          .addComponent(ip, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(all)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(some)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(accept)
          .addComponent(cancel))
        .addContainerGap())
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void allItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_allItemStateChanged
    urls.setEditable(false);
  }//GEN-LAST:event_allItemStateChanged

  private void someItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_someItemStateChanged
    urls.setEditable(true);
  }//GEN-LAST:event_someItemStateChanged

  private void cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelActionPerformed
    dispose();
  }//GEN-LAST:event_cancelActionPerformed

  private void acceptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_acceptActionPerformed
    if (all.isSelected()) {
      urls.setText("all");
    }
    if (!valid(true)) return;
    accepted = true;
    dispose();
  }//GEN-LAST:event_acceptActionPerformed

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton accept;
  private javax.swing.JRadioButton all;
  private javax.swing.ButtonGroup buttonGroup1;
  private javax.swing.JButton cancel;
  private javax.swing.JCheckBox enabled;
  private javax.swing.JTextField ip;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JRadioButton some;
  private javax.swing.JTextArea urls;
  // End of variables declaration//GEN-END:variables

  public boolean accepted = false;

  private boolean isIP4MaskValid(JTextField tf, boolean nullAllowed) {
    String str = tf.getText(), mask = "";
    int test;
    tf.setBackground(new Color(0xff0000));
    if (str.length() == 0) return nullAllowed;
    int idx = str.indexOf("/");
    if (idx == -1) return false;
    mask = str.substring(idx+1);
    str = str.substring(0, idx);
    String octs[] = str.split("[.]", -1);
    if (octs.length != 4) return false;
    try {
      for(int a=0;a<4;a++) {
        test = Integer.valueOf(octs[a]);
        if ((test < 0) || (test > 255)) return false;
      }
      test = Integer.valueOf(mask);
      if ((test < 1) || (test > 32)) return false;
    } catch (Exception e) {
      JFLog.log(e);
      return false;
    }
    tf.setBackground(new Color(0xffffff));
    return true;
  }

  private boolean valid(boolean fixIP) {
    String txt = urls.getText();
    txt = txt.replaceAll("\"", "");
    txt = txt.replaceAll(" ", "");
    txt = txt.replaceAll(",", ".");
    urls.setText(txt);
    if (fixIP) {
      txt = ip.getText();
      int idx = txt.indexOf("/");
      if (idx == -1) {
        txt += "/32";
        ip.setText(txt);
      }
    }
    return isIP4MaskValid(ip, false);
  }

  public String getURLs() {return urls.getText(); }
  public String getIP() { return ip.getText(); }
  public boolean getEnabled() { return enabled.isSelected(); }

  public void keyPressed(KeyEvent e) {}
  public void keyReleased(KeyEvent e) {valid(false);}
  public void keyTyped(KeyEvent e) {}

  private void setPosition() {
    Rectangle s = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
    Dimension d = getSize();
    setLocation(s.width/2 - d.width/2, s.height/2 - (d.height/2));
  }

}
